package com.mission.schedule.my160920;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.mission.schedule.R;
import com.mission.schedule.activity.BaseActivity;
import com.mission.schedule.adapter.FriendsSelectAdapter;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.FriendsBackBean;
import com.mission.schedule.bean.FriendsBean;
import com.mission.schedule.bean.MySchBean;
import com.mission.schedule.bean.UpdateNewFriendMessageBackBean;
import com.mission.schedule.bean.UpdateNewFriendMessageBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.entity.CLNFMessage;
import com.mission.schedule.my160920.bean.FriendBean;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewSchZhuanFaActivity extends BaseActivity implements OnClickListener {
    @ViewResId(id = R.id.top_ll_back)
    private LinearLayout top_ll_back;
    @ViewResId(id = R.id.friends_lv)
    private ListView friends_lv;

    Context context;
    SharedPrefUtil prefUtil = null;
    String userId;
    String path;
    FriendsSelectAdapter adapter = null;
    List<FriendsBean> beansList = new ArrayList<FriendsBean>();
    FriendsBean friendsBean = null;
    MySchBean mySchBean = null;

    String json;

    App app;
    String myName;
    int ID;

    @Override
    protected void setListener() {
        top_ll_back.setOnClickListener(this);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_friendsselect);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;
        prefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        app = App.getDBcApplication();
        userId = prefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERID, "");
        myName = prefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERNAME, "");
        mySchBean = (MySchBean) getIntent().getSerializableExtra("bean");
        com.mission.schedule.cutimage.Log.e("TAG","NewSchZhuanFaActivity");
        LoadData();
    }

    private void LoadData() {
        path = URLConstants.好友列表查询 + "?uId=" + Integer.parseInt(userId);
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            FriendsQueryAsync(path);
        } else {
            Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private void item() {
        friends_lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                friendsBean = (FriendsBean) friends_lv.getAdapter().getItem(
                        position);
                PersonCalerder(mySchBean, friendsBean, friendsBean.fId);
//                app.insertMessageSendData(Integer.parseInt(userId),
//                        friendsBean.fId, 0,
//                        Integer.parseInt(mySchBean.schOpenState), 1,
//                        Integer.parseInt(mySchBean.schIsAlarm),
//                        Integer.parseInt(mySchBean.schIsPostpone), 0,
//                        Integer.parseInt(mySchBean.schDisplayTime),
//                        Integer.parseInt(mySchBean.schBeforeTime),
//                        Integer.parseInt(mySchBean.schSourceType), 0, 0, 0, 0,
//                        0, 0, "", mySchBean.schContent, mySchBean.schDate,
//                        mySchBean.schTime, mySchBean.schSourceDesc,
//                        mySchBean.schSourceDescSpare, mySchBean.schTags,
//                        mySchBean.schRingDesc, mySchBean.schRingCode, "",
//                        mySchBean.schCreateTime, "", "", mySchBean.webUrl,
//                        mySchBean.imgPath, myName, "", 1, 0, 0, "", 0, 0, "",
//                        0, "", DateUtil.formatDateTimeSs(new Date()));
//                ID = app.nfmId;
//                UpdateLoadData();
            }
        });

    }

    @Override
    protected void setAdapter() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_ll_back:
                this.finish();
                break;

            default:
                break;
        }
    }

    private void FriendsQueryAsync(String path) {
        StringRequest request = new StringRequest(Method.GET, path,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new Gson();
                            FriendsBackBean backBean = gson.fromJson(result,
                                    FriendsBackBean.class);
                            if (backBean.status == 0) {
                                if (adapter == null) {
                                    beansList = backBean.tbUserFriendsApp;
                                    if (beansList != null
                                            && beansList.size() > 0) {
                                        adapter = new FriendsSelectAdapter(
                                                context, beansList, R.layout.adapter_friendsselect);
                                        friends_lv.setAdapter(adapter);
                                        item();
                                    } else {
                                        Toast.makeText(context,
                                                "没有好友，赶紧添加几个吧！",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    beansList.clear();
                                    beansList.addAll(backBean.tbUserFriendsApp);
                                    adapter.notifyDataSetChanged();
                                    item();
                                }
                            } else {
                                return;
                            }
                        } else {
                            return;
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    private void alertDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        delete_tv.setText("转发成功！");
        delete_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
                finish();
            }
        });

    }

    private void alertFailDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        delete_tv.setText("转发失败！");
        delete_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.getHttpQueues().cancelAll("down");
    }

    final ProgressUtil progressUtil = new ProgressUtil();

    /**
     * 转发好友日程
     *
     * @param mySchBean
     */
    private void PersonCalerder(final MySchBean mySchBean, final FriendsBean friendsBean, final int cpid) {

        progressUtil.ShowProgress(context, true, true, "正在发送...");
        final JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        final Date date = new Date(System.currentTimeMillis());
        try {
            jsonObject.put("CAlarmsound", mySchBean.schRingCode);
            jsonObject.put("CAlarmsoundDesc", mySchBean.schRingDesc);
            jsonObject.put("CLightAppId", 0);
            jsonObject.put("COpenstate", 1);
            jsonObject.put("CPostpone", Integer.valueOf(mySchBean.schIsPostpone));
            jsonObject.put("CRecommendName", myName);
            jsonObject.put("CTags", "");
            jsonObject.put("CType", 0);
            jsonObject.put("CTypeDesc", mySchBean.schSourceDesc);
            jsonObject.put("CTypeSpare", mySchBean.schSourceDescSpare);
            jsonObject.put("calendaId", 0);
            jsonObject.put("cbeforTime", 0);

            jsonObject.put("cdate", simpleDateFormat.format(date).substring(0, 10));
            jsonObject.put("changTime", simpleDateFormat.format(date));
            jsonObject.put("cisAlarm", 0);
            jsonObject.put("cpId", cpid);
            jsonObject.put("cretetime", simpleDateFormat.format(date));
            jsonObject.put("ctime", simpleDateFormat.format(date).substring(11, 16));

            jsonObject.put("atype", 0);
            jsonObject.put("downNum", 0);
            jsonObject.put("downstate", 0);
            jsonObject.put("endNum", 0);
            jsonObject.put("endState", "0");
            jsonObject.put("id", Integer.valueOf(10000));
            jsonObject.put("imgPath", mySchBean.imgPath);
            jsonObject.put("lyNum", 0);
            jsonObject.put("message", mySchBean.schContent);
            jsonObject.put("parReamrk", "");
            jsonObject.put("pid", "");
            jsonObject.put("poststate", "0");
            jsonObject.put("remark", "");
            jsonObject.put("remark1", android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
            jsonObject.put("remark2", "");
            jsonObject.put("remark3", "");
            jsonObject.put("repCalendaState", 0);
            jsonObject.put("repCalendaTime", "");
            jsonObject.put("repColorType", 0);
            jsonObject.put("repDisplayTime", mySchBean.schDisplayTime);
            jsonObject.put("repInStable", 1);
            jsonObject.put("repIsPuase", 0);
            jsonObject.put("repState", 0);
            jsonObject.put("repType", 0);
            jsonObject.put("repTypeParameter", "");
            jsonObject.put("repdatetwo", "");
            jsonObject.put("repinitialcreatedtime", "");
            jsonObject.put("replastcreatedtime", "");
            jsonObject.put("repnextcreatedtime", "");
            jsonObject.put("repstartdate", "0");

            jsonObject.put("repstatetwo", 0);
            jsonObject.put("schIsImportant", 0);
            jsonObject.put("status", 1);
            jsonObject.put("uid", Integer.valueOf(userId));
            jsonObject.put("webUrl", mySchBean.webUrl);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);

        Log.e("TAG", jsonArray.toString());

        //192.168.2.2:8080 周伟
        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST+"/appFrends_synFrendCalendaNew.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                Log.e("TAG", result);
                                PersonCalerder personCalerder = gson.fromJson(result, PersonCalerder.class);
                                if (personCalerder.status == 0) {
                                    List<PersonCalerderListBean> personCalerderListBeanList = personCalerder.list;
                                    if (personCalerderListBeanList.get(0).getState() == 0) {
                                        addItem(mySchBean, friendsBean, cpid, personCalerderListBeanList.get(0).calendId + "");
                                    } else {
                                        Log.d("TAG", "error:1");
                                        progressUtil.dismiss();
                                        alertFailDialog();
                                        Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Log.d("TAG", "error:2");
                                    progressUtil.dismiss();
                                    alertFailDialog();
                                    Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.d("TAG", "error:3");
                                progressUtil.dismiss();
                                alertFailDialog();
                                Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
                progressUtil.dismiss();
                alertFailDialog();
                Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("data", "{addData:" + jsonArray.toString() + ",updateData:[],deleData:[]}");

                return map;
            }
        };
        stringRequest.setTag("synFrendCalendaNew");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }


    /***
     * 是否返回成功
     *
     * @param response
     * @return
     * @throws JSONException
     */
    public boolean responseCode(String response) throws JSONException {
        int status = 0;
        JSONObject jsonObject = new JSONObject(response);
        int msg = jsonObject.getInt("status");
        return status == msg;
    }


    /**
     * 添加日程
     *
     * @param mySchBean
     * @param cpid      用户id
     * @param calendId  日程id
     */
    private void addItem(MySchBean mySchBean, FriendsBean friendsbean, int cpid, String calendId) {

        /**
         * public int fId;//好友Id
         public int state;//申请好友状态,0是好友1不是好友
         public int uId;//1,用户ID
         public String uName;//好友名称
         public String titleImg;//头像图片地址
         public int type;//0被申请，1表示向别人申请
         public String backImage;//：背景图片
         public int attentionState;//": 0以关注 1没有关注,
         public int redCount;//":未读取数量
         public int readState;
         public int isV;//0 是V 1不是V
         public int attState;//0 以关注1待关注
         public int isFrends;//0 是好友1否
         */

        /***
         * "uid": 52432,
         * "id": 767,
         * "cpId": 260975,
         * "uPersontag": "加油加油！",
         * "uToCode": "iPhone",
         * "remark": null,
         * "uPortrait": "20150925136/638645.jpg",
         * "dateUpdate": "2016-09-05T10:42:55",
         * "uNickName": "韩雪h",
         * "type": 0,
         * "uBackgroundImage": "20160820/933727.png"
         */
        FriendBean friendsBean = new FriendBean();

        friendsBean.setCpId(friendsbean.fId + "");
        friendsBean.setDateUpdate("");
        friendsBean.setId("");
        friendsBean.setRemark("");
        friendsBean.setType("0");
        friendsBean.setuToCode("");
        friendsBean.setuPortrait(friendsbean.titleImg);
        friendsBean.setuPersontag("");
        friendsBean.setuNickName(friendsbean.uName);
        friendsBean.setuBackgroundImage(friendsbean.backImage + "");
        friendsBean.setUid(friendsbean.uId + "");

        if (App.getDBcApplication().queryFriends(friendsbean.fId + "").size() > 0) {
            App.getDBcApplication().insertFriendsList(friendsBean);
        }


        FriendDownAllScheduleBean friendDownAllScheduleBean = new FriendDownAllScheduleBean();

        friendDownAllScheduleBean.setCAlarmsound(mySchBean.schRingCode);
        friendDownAllScheduleBean.setCAlarmsoundDesc(mySchBean.schRingDesc);
        friendDownAllScheduleBean.setCLightAppId("0");
        friendDownAllScheduleBean.setCOpenstate("" + mySchBean.schOpenState);
        friendDownAllScheduleBean.setCPostpone("" + mySchBean.schIsPostpone);
        friendDownAllScheduleBean.setCRecommendName(myName);
        friendDownAllScheduleBean.setCTags("");
        friendDownAllScheduleBean.setCType("0");
        friendDownAllScheduleBean.setCTypeDesc("");
        friendDownAllScheduleBean.setCTypeSpare("");
        friendDownAllScheduleBean.setCalendaId("0");
        friendDownAllScheduleBean.setCbeforTime("0");
        friendDownAllScheduleBean.setCdate(mySchBean.schDate);
        friendDownAllScheduleBean.setChangTime(mySchBean.schCreateTime);
        friendDownAllScheduleBean.setCisAlarm("" + mySchBean.schIsAlarm);
        friendDownAllScheduleBean.setCpId(cpid + "");
        friendDownAllScheduleBean.setCretetime(mySchBean.schCreateTime);
        friendDownAllScheduleBean.setCtime(mySchBean.schTime);

        friendDownAllScheduleBean.setAtype("" + mySchBean.aType);

        friendDownAllScheduleBean.setDownNum("0");
        friendDownAllScheduleBean.setDownstate("0");

        friendDownAllScheduleBean.setEndNum("0");
        friendDownAllScheduleBean.setEndState("0");

        friendDownAllScheduleBean.setId(calendId);
        friendDownAllScheduleBean.setImgPath(mySchBean.imgPath);
        friendDownAllScheduleBean.setLyNum("0");
        friendDownAllScheduleBean.setMessage(mySchBean.schContent);

        friendDownAllScheduleBean.setParReamrk("");
        friendDownAllScheduleBean.setPoststate("");
        friendDownAllScheduleBean.setPid("");

        friendDownAllScheduleBean.setRemark("");
        friendDownAllScheduleBean.setRemark1("" + android.os.Build.MODEL);
        friendDownAllScheduleBean.setRemark2("");
        friendDownAllScheduleBean.setRemark3("");
        friendDownAllScheduleBean.setRepCalendaState("0");
        friendDownAllScheduleBean.setRepCalendaTime("0");
        friendDownAllScheduleBean.setRepColorType("0");
        friendDownAllScheduleBean.setRepDisplayTime("" + mySchBean.schDisplayTime);
        friendDownAllScheduleBean.setRepInStable("0");
        friendDownAllScheduleBean.setRepIsPuase("0");
        friendDownAllScheduleBean.setRepState("0");
        friendDownAllScheduleBean.setRepType("0");
        friendDownAllScheduleBean.setRepTypeParameter("");
        friendDownAllScheduleBean.setRepdatetwo("0");
        friendDownAllScheduleBean.setRepinitialcreatedtime("");
        friendDownAllScheduleBean.setReplastcreatedtime("");
        friendDownAllScheduleBean.setRepnextcreatedtime("");
        friendDownAllScheduleBean.setRepstartdate("");
        friendDownAllScheduleBean.setRepState("");

        friendDownAllScheduleBean.setSchIsImportant("0");
        friendDownAllScheduleBean.setStatus("1");

        friendDownAllScheduleBean.setUid(userId);
        friendDownAllScheduleBean.setWebUrl("" + mySchBean.webUrl);


        App.getDBcApplication().insertFriendSchedule(friendDownAllScheduleBean);


        progressUtil.dismiss();
        Intent intent = new Intent();
        intent.setAction("add");
        intent.putExtra("cpid", cpid);
        sendBroadcast(intent);
        alertDialog();
    }


    /**
     * 修改,删除,新增返回
     */
    public class PersonCalerder {

        /**
         * list : [{"id":1114,"calendId":857,"state":0,"dataState":1,"downTime":"2016-09-22 16:37:00"}]
         * message : 成功
         * status : 0
         */

        public String message;
        public int status;
        /**
         * id : 1114
         * calendId : 857
         * state : 0
         * dataState : 1
         * downTime : 2016-09-22 16:37:00
         */

        public List<PersonCalerderListBean> list;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<PersonCalerderListBean> getList() {
            return list;
        }

        public void setList(List<PersonCalerderListBean> list) {
            this.list = list;
        }


    }

    public class PersonCalerderListBean {
        private int id;
        private int calendId;
        private int state;
        private int dataState;
        private String downTime;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getCalendId() {
            return calendId;
        }

        public void setCalendId(int calendId) {
            this.calendId = calendId;
        }

        public int getState() {
            return state;
        }

        public void setState(int state) {
            this.state = state;
        }

        public int getDataState() {
            return dataState;
        }

        public void setDataState(int dataState) {
            this.dataState = dataState;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }
    }

}
